//
//  FamousListVideoViewController.m
//  ShangHaiTuJI
//
//  Created by xiaoxiangtuji on 2017/8/12.
//  Copyright © 2017年 xiaoxiangtuji. All rights reserved.
//

#import "FamousListVideoViewController.h"
#import "FamousListCell.h"
#import "MusicManager.h"
#import "OpusListModel.h"
#import "BigIntellgientModel.h"
@interface FamousListVideoViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)UISlider *slider;
@property(nonatomic,strong)UILabel *CurrentTimeLabel;
@property(nonatomic,strong)UILabel *totlaLabel;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,strong)UIView *headerView;
@property(nonatomic,strong)UIImageView *imageView;
@end

@implementation FamousListVideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
     [self createTableViewUI];
     [self createAvPlayerView];
    // Do any additional setup after loading the view.
}
#pragma mark -创建音频播放器
-(void)createAvPlayerView{
    _slider = [[UISlider alloc] init];
    [_slider addTarget:self action:@selector(progressAct:) forControlEvents:UIControlEventValueChanged];
    [_headerView addSubview:_slider];
    [_slider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_headerView);
        make.top.equalTo(_imageView.mas_bottom);
        make.height.mas_equalTo(scaleTopAndBottom(3));
        
    }];
    _CurrentTimeLabel = [[UILabel alloc] init];
    _CurrentTimeLabel.textAlignment = NSTextAlignmentLeft;
    _CurrentTimeLabel.text = @"00:00";
    [_headerView addSubview:_CurrentTimeLabel];
    [_CurrentTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_headerView);
        make.top.equalTo(_slider.mas_bottom);
        make.size.mas_equalTo(CGSizeMake(scaleLeftAndRight(100), scaleTopAndBottom(10)));
    }];
    _totlaLabel = [[UILabel alloc] init];
    _totlaLabel.textAlignment = NSTextAlignmentRight;
    [_headerView addSubview:_totlaLabel];
    [_totlaLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_headerView);
        make.top.equalTo(_slider.mas_bottom);
        make.size.mas_equalTo(CGSizeMake(scaleLeftAndRight(100), scaleTopAndBottom(10)));
    }];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAct) userInfo:nil repeats:YES];
    
}
-(void)progressAct:(id)sender{
    [[MusicManager shareInfo] playerProgressWithProgressFloat:((UISlider*)sender).value];
}
- (void)timerAct{
    if ([MusicManager shareInfo].player.currentTime.timescale == 0 || [MusicManager shareInfo].player.currentItem.duration.timescale == 0) {
        return;
    }

    // 获得音乐总时长
    long long int totalTime = [MusicManager shareInfo].player.currentItem.duration.value / [MusicManager shareInfo].player.currentItem.duration.timescale;
    // 获得当前时间
    long long int currentTime = [MusicManager shareInfo].player.currentTime.value / [MusicManager shareInfo].player.currentTime.timescale;
    self.CurrentTimeLabel.text = [NSString stringWithFormat:@"%02lld:%02lld", currentTime / 60, currentTime % 60];
    self.totlaLabel.text = [NSString stringWithFormat:@"%02lld:%02lld", totalTime / 60, totalTime % 60];
    self.slider.maximumValue = totalTime;
    self.slider.minimumValue = 0;
    self.slider.value = currentTime;
    if (self.slider.value == totalTime) {
        [[MusicManager shareInfo] playNext];
        //        [self reloadDataWithIndex:[MusicManager shareInfo].index];
    }
}

//创建头部视图
-(void)createTableViewUI{
    /*******************设置头部视图的播放音频的页面******************************/
    _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, WIDTH, scaleTopAndBottom(210))];
    
    _headerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_headerView];
    _imageView = [[UIImageView alloc] init];
    _imageView.backgroundColor = [UIColor redColor];
    [_headerView addSubview:_imageView];
    [_imageView sd_setImageWithURL:[NSURL URLWithString:self.imagePath] placeholderImage:[UIImage imageNamed:@""]];
    [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(_headerView);
        make.height.mas_equalTo(scaleTopAndBottom(210));
    }];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,scaleTopAndBottom(210) + 64, WIDTH, HEIGHT - 64 - scaleTopAndBottom(210)) style:UITableViewStylePlain];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
    }];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[FamousListCell class] forCellReuseIdentifier:@"FamousListCell"];
    self.tableView.estimatedRowHeight = 200;
    [self.tableView reloadData];
}
#pragma mark -tableView的代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    FamousListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FamousListCell"];
    OpusListModel *model = self.dataArray[indexPath.row];
    cell.titlelabel.text = [NSString stringWithFormat:@"%ld  %@",(long)indexPath.row,model.name];
    return cell;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor cyanColor];
    UILabel *lable = [[UILabel alloc] init];
    lable.text = @"音频列表";
    [view addSubview:lable];
    [lable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.bottom.equalTo(view);
        make.left.equalTo(view.mas_left).offset(scaleLeftAndRight(10));
    }];
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return scaleTopAndBottom(50);
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return scaleTopAndBottom(60);
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    OpusListModel *model = self.dataArray[indexPath.row];
    [[MusicManager shareInfo] replaceItemWithUrlString:model.filepath];
    [self getDetailInformationAccordingOpusId:model.opusId];
    if (self.sendIdBlock) {
        self.sendIdBlock(model.opusId);
    }
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshFamousDetail" object:nil userInfo:@{@"FILEID":model.opusId}];
}
/**
 获取头部视图的界面

 
 */

-(void)getDetailInformationAccordingOpusId:(NSString *)opusId{
    dispatch_queue_t gloabQue = dispatch_get_global_queue(0, 0);
    dispatch_async(gloabQue, ^{
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        NSDictionary *param = @{@"id":opusId};
        NSString *url = ServerIp@"/opusApp/detail";
        [manager POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            BigIntellgientModel *model = [BigIntellgientModel modelWithDictionary:jsonDic];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.imageView sd_setImageWithURL:[NSURL URLWithString:model.imagepath] placeholderImage:[UIImage imageNamed:@""]];
            });
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];

    });
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
